<template>
  <div class="books-view">
    <h1 class="page-title">
      <Icon icon="lucide:book" width="28" height="28" />
      图书管理
    </h1>

    <!-- 搜索栏 -->
    <el-card class="card-container" style="margin-bottom: 24px;">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="书籍标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入书籍标题"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>

        <el-form-item label="作者">
          <el-input
            v-model="searchForm.author"
            placeholder="请输入作者"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable @clear="handleSearch">
            <el-option label="文学" value="LITERATURE" />
            <el-option label="科技" value="TECHNOLOGY" />
            <el-option label="历史" value="HISTORY" />
            <el-option label="艺术" value="ART" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="RefreshLeft" @click="resetSearch">重置</el-button>
          <el-button v-if="userRole === 'ADMIN'" type="success" :icon="Plus" @click="handleAdd">添加书籍</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 书籍列表 -->
    <el-card class="card-container">
      <el-table
        :data="bookList"
        stripe
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />

        <el-table-column prop="title" label="书籍标题" min-width="200">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; gap: 12px;">
              <el-avatar
                v-if="row.coverImage"
                :size="40"
                :src="row.coverImage"
                shape="square"
              />
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="author" label="作者" width="120" />

        <el-table-column prop="publisher" label="出版社" width="150" />

        <el-table-column prop="category" label="分类" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)">
              {{ getCategoryName(row.category) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="totalQuantity" label="库存" width="100" align="center" />

        <el-table-column prop="availableQuantity" label="可借" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.availableQuantity > 0 ? 'success' : 'danger'">
              {{ row.availableQuantity }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="180" />

        <el-table-column v-if="userRole === 'ADMIN'" label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="table-actions">
              <el-button size="small" @click="handleView(row)">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column v-else label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              :disabled="row.availableQuantity <= 0"
              @click="handleBorrow(row)"
            >
              借阅
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; display: flex; justify-content: flex-end;">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加书籍' : '编辑书籍'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="bookFormRef"
        :model="bookForm"
        :rules="bookRules"
        label-width="100px"
      >
        <el-form-item label="书籍标题" prop="title">
          <el-input v-model="bookForm.title" placeholder="请输入书籍标题" />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input v-model="bookForm.author" placeholder="请输入作者" />
        </el-form-item>

        <el-form-item label="出版社">
          <el-input v-model="bookForm.publisher" placeholder="请输入出版社" />
        </el-form-item>

        <el-form-item label="出版日期">
          <el-input v-model="bookForm.publishDate" placeholder="请输入出版日期" />
        </el-form-item>

        <el-form-item label="ISBN">
          <el-input v-model="bookForm.isbn" placeholder="请输入ISBN编号" />
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select v-model="bookForm.category" placeholder="请选择分类" style="width: 100%;">
            <el-option label="文学" value="LITERATURE" />
            <el-option label="科技" value="TECHNOLOGY" />
            <el-option label="历史" value="HISTORY" />
            <el-option label="艺术" value="ART" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>

        <el-form-item label="库存数量" prop="totalQuantity">
          <el-input-number v-model="bookForm.totalQuantity" :min="0" style="width: 100%;" />
        </el-form-item>

        <el-form-item label="书籍描述">
          <el-input
            v-model="bookForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入书籍描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          {{ dialogType === 'add' ? '添加' : '更新' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, RefreshLeft } from '@element-plus/icons-vue'
import { Icon } from '@iconify/vue'
import { useAuthStore } from '@/store/auth'
import {
  getBooks,
  addBook,
  updateBook,
  deleteBook,
  borrowBook
} from '@/api/books'

const authStore = useAuthStore()
const userRole = computed(() => authStore.user?.role)

const loading = ref(false)
const submitLoading = ref(false)
const bookList = ref([])

const searchForm = reactive({
  title: '',
  author: '',
  category: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const bookFormRef = ref()

const bookForm = reactive({
  title: '',
  author: '',
  publisher: '',
  publishDate: '',
  isbn: '',
  category: '',
  description: '',
  totalQuantity: 0
})

const bookRules = {
  title: [{ required: true, message: '请输入书籍标题', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  totalQuantity: [{ required: true, message: '请输入库存数量', trigger: 'blur' }]
}

const loadBooks = async () => {
  loading.value = true
  try {
    const response = await getBooks({
      current: pagination.current,
      size: pagination.size,
      title: searchForm.title,
      author: searchForm.author,
      category: searchForm.category
    })

    if (response.data.code === 200) {
      bookList.value = response.data.data.records
      pagination.total = response.data.data.total
    }
  } catch (error) {
    console.error('加载书籍列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadBooks()
}

const resetSearch = () => {
  searchForm.title = ''
  searchForm.author = ''
  searchForm.category = ''
  pagination.current = 1
  loadBooks()
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadBooks()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadBooks()
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(bookForm).forEach(key => {
    bookForm[key] = ''
  })
  bookForm.totalQuantity = 0
  bookForm.category = ''
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(bookForm, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  // TODO: 实现查看详情
  ElMessage.info('查看详情功能开发中...')
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除《${row.title}》吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteBook(row.id)
    ElMessage.success('删除成功')
    loadBooks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleBorrow = async (row) => {
  try {
    // 获取当前用户ID（简化处理，实际应该从token中解析）
    const userId = authStore.user?.id

    await ElMessageBox.confirm(
      `确定要借阅《${row.title}》吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    await borrowBook({
      userId: userId,
      bookId: row.id,
      borrowDays: 30
    })

    ElMessage.success('借阅成功')
    loadBooks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '借阅失败')
    }
  }
}

const handleSubmit = async () => {
  if (!bookFormRef.value) return

  await bookFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'add') {
          await addBook(bookForm)
          ElMessage.success('添加成功')
        } else {
          await updateBook(bookForm.id, bookForm)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadBooks()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const getCategoryName = (category) => {
  const map = {
    'LITERATURE': '文学',
    'TECHNOLOGY': '科技',
    'HISTORY': '历史',
    'ART': '艺术',
    'OTHER': '其他'
  }
  return map[category] || category
}

const getCategoryTagType = (category) => {
  const map = {
    'LITERATURE': 'info',
    'TECHNOLOGY': 'primary',
    'HISTORY': 'warning',
    'ART': 'success',
    'OTHER': 'default'
  }
  return map[category] || 'default'
}

onMounted(() => {
  loadBooks()
})
</script>

<style scoped>
.books-view {
  padding: 0;
}

.table-actions {
  display: flex;
  gap: 8px;
}
</style>
